<?php
namespace app\controller\student;

use app\BaseController;
use app\model\Chapter;
use app\model\Media;
use app\model\StudentCourse;
use app\model\StudentMedia;
use \think\facade\Db;

/**
 * 学生章节媒体控制器
 */
class StudentChapterMedia extends BaseController
{

    /**
     * 章节列表
     */
    public function list()
    {
        $courseID=$this->request->param('courseID');
        $studentCourse = StudentCourse::where(["SID"=>$this->user['SID'],"courseID",$courseID]);
        if(empty($studentCourse)){
            return json("no permission");
        }
        //验证学生对该章节的权限
        $chapter = Db::name('chapter')
        ->where('courseID',$courseID)
        ->select()->toArray();
        $chapterID = array_column($chapter,'chapterID');
        $media = Db::name('media')->where('chapterID','in',$chapterID)->select()->toArray();
        $data = [];
        foreach($chapter as $cp){
            $data[$cp['chapterID']] = $cp;
            $data[$cp['chapterID']]['media']=[];
        }
        foreach($media as $md){
            $studentMedia = StudentMedia::where(['SID'=>$this->user['SID'],'MID'=>$md['MID']])->find();
            if($studentMedia) $md['isDone'] = true;
            else $md['isDone'] = false;
            $data[$md['chapterID']]['media'][] = $md;
        }
        return resultSuccess(array_values($data));
    }

    /**
     * 播放完成
     */
    public function viewed(){
        $MID = $this->request->param('MID');
        $media = Media::find($MID);
        if($media == null){
            return resultError();
        }
        $chapterID = $media->chapterID;
        $chapter = Chapter::find($chapterID);
        $courseID = $chapter->courseID;
        $studentCourse =StudentCourse::where(['SID'=>$this->user['SID'],'courseID'=>$courseID])->find();
        if($studentCourse == null) return resultError('无此权限');
        $studentMedia = new StudentMedia([
            'SID'=>$this->user['SID'],
            'MID'=>$MID
        ]);
        if($studentMedia->replace()->save()){
            return resultSuccess();
        }
        return resultError();
    }

}
